package com.bang.daybreak.security.config.handler;

import com.bang.daybreak.common.util.JacksonUtils;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * <p>
 * AuthenticationEntryPoint 用来解决匿名用户访问无权限资源时的异常
 * </p>
 *
 * @version 1.0
 * @author: wdj
 * @date: 2019/8/10 0010 下午 17:15
 */
@Component
public class GuestAuthenticationEntryPoint implements AuthenticationEntryPoint {

    /**
     * 无权限访问返回json数据
     *
     * @param httpServletRequest
     * @param httpServletResponse
     * @param e
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
        Map<String, Object> map = new LinkedHashMap<String, Object>();
        map.put("httpCode", HttpStatus.UNAUTHORIZED.value());
        map.put("error", "USER_NEED_AUTHORITIES");
        map.put("msg", "您未登录，请重新登录!");
        httpServletResponse.setCharacterEncoding("UTF-8");
        httpServletResponse.setContentType("application/json;charset=UTF-8");
        httpServletResponse.setStatus(HttpStatus.UNAUTHORIZED.value());
        httpServletResponse.getWriter().write(JacksonUtils.toJson(map));
    }

}
